Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[CSS] div 垂直水平置中簡單的兩個方法

發表於 2017-09-04 更新於 2019-08-21 分類於 CSS

繼上次的自製Dimmer突然發現一個問題,如果我的modal要垂直和水平都置中的話怎麼辦呢?

網路上一查就有一堆文章,我喜歡越簡單的越好,就介紹下面兩個:

子元素加上 margin: auto;

直接看範例吧~

1
2
3
<div class="father">
<div class="son">Hello world!</div>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.father {
position: relative;
background-color: rgba(0, 0, 0, 0.53);
width: 100%;
height: 100%;
position: fixed;
z-index: 2;
}
.son {
position: absolute;
width: 100px;
height: 50px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: #fff;
z-index: 3;
}

父元素使用 display: flex;

直接看範例吧~

1
2
3
<div class="father">
<div class="son">Hello world!</div>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.father {
display:flex;
align-items:center;
justify-content:center;
background-color: rgba(0, 0, 0, 0.53);
width: 100%;
height: 100%;
position: fixed;
z-index: 2;
}
.son {
position: relative;
width: 100px;
height: 50px;
background: #fff;
z-index: 3;
}

##參考文章
CSS 垂直置中的七個方法

# CSS # 垂直水平置中
[Vue2]vue file scss 使用 & RWD 被覆蓋 小觀念紀錄
[element-ui]移除 el-form-item 上 required 的星號 (米字, *)
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 子元素加上 margin: auto;
  2. 2. 父元素使用 display: flex;
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0